<template>
  <div class="table-page">
    <GiTable title="设备资源管理" row-key="id" :data="dataList" :columns="columns" :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }" :pagination="pagination" :disabled-tools="['size']"
      :disabled-column-keys="['name']" @refresh="search">
      <template #toolbar-left>
        <a-input v-model="queryForm.deviceName" placeholder="请输入设备名称" allow-clear @change="search">
          <template #prefix><icon-search /></template>
        </a-input>
        <a-select v-model="queryForm.category" :options="category_enum" placeholder="请选择设备类别" allow-clear
          style="width: 150px" @change="search" />
        <a-input v-model="queryForm.modelId" placeholder="请输入型号" allow-clear @change="search">
          <template #prefix><icon-search /></template>
        </a-input>
        <a-input v-model="queryForm.factoryId" placeholder="请输入出厂编号" allow-clear @change="search">
          <template #prefix><icon-search /></template>
        </a-input>
        <a-date-picker v-model="queryForm.buyDate" placeholder="请选择购置时间" show-time format="YYYY-MM-DD HH:mm:ss"
          style="height: 32px" />
        <a-button @click="reset">
          <template #icon><icon-refresh /></template>
          <template #default>重置</template>
        </a-button>
      </template>
      <template #toolbar-right>
        <a-button v-permission="['generator:deviceStore:add']" type="primary" @click="onAdd">
          <template #icon><icon-plus /></template>
          <template #default>新增</template>
        </a-button>
        <a-button v-permission="['generator:deviceStore:import']" @click="onImport">
          <template #icon><icon-upload /></template>
          <template #default>导入</template>
        </a-button>
        <a-button v-permission="['generator:deviceStore:export']" @click="onExport">
          <template #icon><icon-download /></template>
          <template #default>导出</template>
        </a-button>
        <a-button v-permission="['generator:deviceStore:export']" status="warning" @click="onExportExpiring">
          <template #icon><icon-download /></template>
          <template #default>导出即将到期清单</template>
        </a-button>
        <a-button v-permission="['generator:deviceStore:delete']" status="danger" @click="onOrganize">
          <template #icon><icon-delete /></template>
          <template #default>整理</template>
        </a-button>
      </template>

      <!-- 设备类别列插槽 -->
      <template #category="{ record }">
        <a-tag :color="getCategoryColor(record.category)" bordered class="category-tag">
          {{ getCategoryName(record.category) }}
        </a-tag>
      </template>

      <!-- 计量单位列插槽 - 使用方案一（彩色标签） -->
      <template #measureUnit="{ record }">
        <a-tag :color="getUnitColor(record.measureUnit)" bordered>
          {{ getMeasureUnitName(record.measureUnit) }}
        </a-tag>
      </template>



      <!-- 状态列插槽 - 使用下拉菜单 -->
      <template #status="{ record }">
        <a-dropdown 
          :trigger="['click']" 
          position="bl"
          @select="(status) => handleStatusChange(record as DeviceStoreResp, parseInt(status as string))"
        >
          <span class="status-badge" :class="`status-${(record as DeviceStoreResp).status}`">
            <span class="status-dot"></span>
            {{ getStatusName(typeof (record as DeviceStoreResp).status === 'number' ? (record as DeviceStoreResp).status : parseInt(String((record as DeviceStoreResp).status || '0'))) }}
          </span>
          <template #content>
            <a-doption 
              v-for="statusOption in statusOptions" 
              :key="statusOption.value"
              :value="statusOption.value"
              :class="{ 'selected': (typeof (record as DeviceStoreResp).status === 'number' ? (record as DeviceStoreResp).status : parseInt(String((record as DeviceStoreResp).status || '0'))) === statusOption.value }"
            >
              <span class="status-option">
                <span class="status-dot" :style="{ backgroundColor: getStatusColor(statusOption.value) }"></span>
                {{ statusOption.label }}
              </span>
            </a-doption>
          </template>
        </a-dropdown>
      </template>

      <!-- 物资去向列插槽 - 使用方案一（彩色标签） -->
      <template #destination="{ record }">
        <a-tag :color="getDestinationColor(record.destination)" bordered>
          {{ getDestinationName(record.destination) }}
        </a-tag>
      </template>

      <!-- 校准有效期列插槽 - 添加到期提示 -->
      <template #checkoutDate="{ record }">
        <div v-if="record.checkoutDate" :class="getExpiringClass(record.checkoutDate)">
          <a-tooltip v-if="isExpiringSoon(record.checkoutDate)" :content="getExpiringTooltip(record.checkoutDate)">
            <span style="display: inline-flex; align-items: center; gap: 4px;">
              <icon-exclamation-circle-fill style="color: #f53f3f;" />
              {{ formatDate(record.checkoutDate) }}
            </span>
          </a-tooltip>
          <span v-else>{{ formatDate(record.checkoutDate) }}</span>
        </div>
        <span v-else>--</span>
      </template>

      <template #action="{ record }">
        <a-space>
          <a-link v-permission="['generator:deviceStore:detail']" title="详情" @click="onDetail(record)">
            详情
          </a-link>
          <a-link v-permission="['generator:deviceStore:update']" title="修改" @click="onUpdate(record)">
            修改
          </a-link>
          <a-link v-permission="['generator:deviceStore:delivery']" status="warning" title="出库"
            @click="onDelivery(record)">
            出库
          </a-link>
          <a-link v-permission="['generator:deviceStore:delete']" status="danger" :disabled="record.disabled"
            :title="record.disabled ? '不可删除' : '删除'" @click="onDelete(record)">
            删除
          </a-link>
        </a-space>
      </template>

    </GiTable>

    <DeviceStoreAddModal ref="DeviceStoreAddModalRef" @save-success="search" />
    <DeviceStoreDetailDrawer ref="DeviceStoreDetailDrawerRef" />
    <DeviceStoreDeliveryModal ref="DeliveryModalRef" @delivery-success="search" />
    <DeviceStoreImportDrawer ref="DeviceStoreImportDrawerRef" @save-success="search" />
  </div>
</template>

<script setup lang="ts">
import DeviceStoreAddModal from './DeviceStoreAddModal.vue'
import DeviceStoreDeliveryModal from './DeviceStoreDeliveryModal.vue'
import DeviceStoreDetailDrawer from './DeviceStoreDetailDrawer.vue'
import DeviceStoreImportDrawer from './DeviceStoreImportDrawer.vue'
import { useDownload, useTable } from '@/hooks'
import { useDict } from '@/hooks/app'
import { isMobile } from '@/utils'
import has from '@/utils/has'
import {
  type DeviceStoreResp,
  type DeviceStoreQuery,
  type DeliveryRequest,
  deleteDeviceStore,
  exportDeviceStore,
  listDeviceStore,
  exportExpiringDeviceStore,
  organizeDeviceStore
} from '@/apis/generator/deviceStore'
import type { TableInstanceColumns } from '@/components/GiTable/type'
import { Message, Modal, Notification } from '@arco-design/web-vue'
import { updateDeviceStatus } from '@/apis/generator/deviceStore'
import dayjs from 'dayjs'

defineOptions({ name: 'DeviceStore' })

// 数字映射字典
const categoryMap: Record<number, string> = {
  0: '传感器',
  1: '仪器仪表',
  2: '动态采集系统',
  3: '信息化设备',
  4: '耗材',
  5: '其他设备',
}

const measureUnitMap: Record<number, string> = {
  0: '台',
  1: '支',
  2: '个',
}

const statusMap: Record<number, string> = {
  0: '归还',
  3: '报废',
}

// 状态选项
const statusOptions = [
  { value: 0, label: '归还' },
  { value: 3, label: '报废' }
]

const destinationMap: Record<number, string> = {
  0: '周转库',
  1: '外借',
  2: '其他',
}
const getCategoryColor = (category: number): string => {
  const colors = ['#3498db', '#2ecc71', '#9b59b6', '#e67e22', '#1abc9c', '#34495e']
  return colors[category] || '#95a5a6'
}

const getStatusColor = (status: number): string => {
  const colors = ['#2ecc71', '#3498db', '#f39c12', '#e74c3c']
  return colors[status] || '#95a5a6'
}

/**
 * 处理状态变更
 */
const handleStatusChange = async (record: DeviceStoreResp, newStatus: number) => {
  const currentStatus = typeof record.status === 'number' ? record.status : parseInt(String(record.status || '0'))
  if (currentStatus === newStatus) {
    return // 状态未改变，直接返回
  }

  const statusName = getStatusName(newStatus)
  const oldStatusName = getStatusName(currentStatus)
  
  Modal.confirm({
    title: '确认修改状态',
    content: `确定要将设备 ${record.deviceName} (编号: ${record.managementId}) 的状态从【${oldStatusName}】修改为【${statusName}】吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        loading.value = true
        const res = await updateDeviceStatus(record.id, newStatus)
        
        // 检查响应结果
        if (res && res.success === false) {
          const errorMsg = res.data?.message || res.msg || '状态修改失败'
          Message.error(errorMsg)
          return
        }
        
        Message.success(res?.data?.message || res?.msg || '状态修改成功')
        await search() // 刷新数据
      } catch (error: any) {
        console.error('状态修改失败:', error)
        // 从错误对象中提取错误信息，优先使用 message 字段（后端返回的字段）
        const errorMsg = error?.message || error?.msg || error?.response?.data?.message || error?.response?.data?.msg || '状态修改失败，请重试'
        Message.error(errorMsg)
      } finally {
        loading.value = false
      }
    }
  })
}

const getUnitColor = (unit: number): string => {
  const colors = ['#1abc9c', '#3498db', '#9b59b6']
  return colors[unit] || '#95a5a6'
}

const getDestinationColor = (destination: number | null | undefined): string => {
  if (destination === null || destination === undefined) return '#95a5a6'
  const colors = ['#2ecc71', '#f39c12', '#95a5a6']
  return colors[destination] || '#95a5a6'
}


// 字典转换方法
const getCategoryName = (category: number): string => categoryMap[category] || String(category)
const getMeasureUnitName = (unit: number): string => measureUnitMap[unit] || String(unit)
const getStatusName = (status: number): string => statusMap[status] || String(status)
const getDestinationName = (destination: number | null | undefined): string => {
  // 处理空值
  if (destination === null || destination === undefined) return '--';
  // 正常映射
  return destinationMap[destination] || String(destination);
}
const DeviceStoreImportDrawerRef = ref<InstanceType<typeof DeviceStoreImportDrawer>>()
// 导入
const onImport = () => {
  DeviceStoreImportDrawerRef.value?.onOpen()
}
// 设备类别枚举（用于下拉选择框）
const category_enum = [
  { value: 0, label: '传感器' },
  { value: 1, label: '仪器仪表' },
  { value: 2, label: '动态采集系统' },
  { value: 3, label: '信息化设备' },
  { value: 4, label: '耗材' },
  { value: 5, label: '其他设备' }
]

const queryForm = reactive<DeviceStoreQuery>({
  deviceName: undefined,
  category: undefined,
  modelId: undefined,
  factoryId: undefined,
  buyDate: undefined,
  sort: ['id,desc']
})



const columns: TableInstanceColumns[] = [
  { title: '设备名称', dataIndex: 'deviceName', slotName: 'deviceName', width: 100 },
  {
    title: '设备类别',
    dataIndex: 'categoryDisplay',
    slotName: 'category',
    width: 100
  },
  { title: '管理编号', dataIndex: 'managementId', slotName: 'managementId', width: 100 },
  { title: '型号', dataIndex: 'modelId', slotName: 'modelId', width: 100 },
  { title: '出厂编号', dataIndex: 'factoryId', slotName: 'factoryId', width: 100 },
  {
    title: '计量单位',
    dataIndex: 'measureUnitDisplay',
    slotName: 'measureUnit',
    width: 100
  },
  { title: '库存数量', dataIndex: 'count', slotName: 'count', width: 100 },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 120,
    tooltip: '点击状态可快速修改'
  },
  { title: '放置位置', dataIndex: 'location', slotName: 'location', width: 120 },
  { title: '购置来源', dataIndex: 'source', slotName: 'source', width: 120 },
  { title: '购置时间', dataIndex: 'buyDate', slotName: 'buyDate', width: 120 },
  { title: '生产厂家', dataIndex: 'manufacturer', slotName: 'manufacturer', width: 100 },
  { title: '购置金额', dataIndex: 'purchaseAmount', slotName: 'purchaseAmount', width: 120 },
  { title: '备注', dataIndex: 'remark', slotName: 'remark', width: 100 },
  {
    title: '物资去向',
    dataIndex: 'destinationDisplay',
    slotName: 'destination',
    width: 120
  },
  {
    title: '校准有效期',
    dataIndex: 'checkoutDate',
    slotName: 'checkoutDate',
    width: 120
  },
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'action',
    width: 200, // 增加了宽度以适应新按钮
    align: 'center',
    fixed: !isMobile() ? 'right' : undefined,
    show: has.hasPermOr([
      'generator:deviceStore:detail',
      'generator:deviceStore:update',
      'generator:deviceStore:delivery',
      'generator:deviceStore:delete'
    ])
  }
]

const reset = () => {
  queryForm.deviceName = ""
  queryForm.category = ""
  queryForm.modelId = ""
  queryForm.factoryId = ""
  queryForm.buyDate = ""
  search()
}

const {
  tableData: dataList,
  loading,
  pagination,
  search,
  handleDelete
} = useTable((page) =>
  listDeviceStore({ ...queryForm, ...page }).then(res => {
    // 检查即将到期的设备并提示
    checkExpiringDevices(res.list || [])
    return res
  }),
  { immediate: true }
)

// 格式化日期
const formatDate = (dateStr?: string | null): string => {
  if (!dateStr) return '--'
  return dayjs(dateStr).format('YYYY-MM-DD')
}

// 判断是否即将到期（距离校准有效期前一个月）
const isExpiringSoon = (checkoutDate?: string | null): boolean => {
  if (!checkoutDate) return false
  const expiryDate = dayjs(checkoutDate)
  const oneMonthLater = dayjs().add(1, 'month')
  const now = dayjs()
  // 如果校准有效期在未来一个月内，且未过期
  return expiryDate.isAfter(now) && expiryDate.isBefore(oneMonthLater) || expiryDate.isSame(oneMonthLater, 'day')
}

// 获取到期提示样式类
const getExpiringClass = (checkoutDate?: string | null): string => {
  if (isExpiringSoon(checkoutDate)) {
    return 'expiring-soon'
  }
  if (checkoutDate && dayjs(checkoutDate).isBefore(dayjs())) {
    return 'expired'
  }
  return ''
}

// 获取到期提示文本
const getExpiringTooltip = (checkoutDate?: string | null): string => {
  if (!checkoutDate) return ''
  const expiryDate = dayjs(checkoutDate)
  const daysLeft = expiryDate.diff(dayjs(), 'day')
  if (daysLeft < 0) {
    return `已过期 ${Math.abs(daysLeft)} 天`
  }
  return `距离校准有效期还有 ${daysLeft} 天`
}

// 检查即将到期的设备并提示
const checkExpiringDevices = (devices: DeviceStoreResp[]) => {
  const expiringDevices = devices.filter(device => isExpiringSoon(device.checkoutDate))
  if (expiringDevices.length > 0) {
    Notification.warning({
      title: '即将到期设备提醒',
      content: `检测到 ${expiringDevices.length} 个设备即将在30天内到期，请及时处理。`,
      duration: 5000
    })
  }
}

// 导出即将到期设备清单
const onExportExpiring = () => {
  useDownload(() => exportExpiringDeviceStore(queryForm))
}

const onOrganize = async () => {
  Modal.confirm({
    title: '确认整理',
    content: '整理操作将删除隐形数据，是否继续？',
    onOk: async () => {
      try {
        const res = await organizeDeviceStore()
        if (res.success) {
          const deletedCount = res.data || 0
          Message.success(`整理完成，共删除 ${deletedCount} 个设备`)
          search()
        } else {
          Message.error(res.message || '整理失败')
        }
      } catch (error: any) {
        Message.error(error.message || '整理失败')
      }
    }
  })
}

const onDelete = (record: DeviceStoreResp) => {
  return handleDelete(() => deleteDeviceStore(record.id), {
    content: `是否确定删除该条数据？`,
    showModal: true
  })
}

const onExport = () => {
  useDownload(() => exportDeviceStore(queryForm))
}

const DeviceStoreAddModalRef = ref<InstanceType<typeof DeviceStoreAddModal>>()
const onAdd = () => {
  DeviceStoreAddModalRef.value?.onAdd()
}

const onUpdate = (record: DeviceStoreResp) => {
  DeviceStoreAddModalRef.value?.onUpdate(record.id)
}
const DeliveryModalRef = ref<InstanceType<typeof DeviceStoreDeliveryModal>>()
const onDelivery = (record: DeviceStoreResp) => {
  DeliveryModalRef.value?.open(record)
}
const DeviceStoreDetailDrawerRef = ref<InstanceType<typeof DeviceStoreDetailDrawer>>()
const onDetail = (record: DeviceStoreResp) => {
  DeviceStoreDetailDrawerRef.value?.onOpen(record.id)
}
</script>

<style scoped lang="scss">
.table-page .ant-table th,
.table-page .ant-table td {
  padding: 8px;
}

.table-page .ant-table th {
  white-space: normal;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
  background-color: currentColor;
}

/* 渐变背景色 - 状态标签 */
.status-badge {
  padding: 2px 8px;
  border-radius: 4px;
  color: white;
  font-size: 12px;
  display: inline-flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  }

  &.status-0 {
    background: linear-gradient(135deg, #2ecc71, #27ae60);
  }

  &.status-1 {
    background: linear-gradient(135deg, #3498db, #2980b9);
  }

  &.status-2 {
    background: linear-gradient(135deg, #f39c12, #e67e22);
  }

  &.status-3 {
    background: linear-gradient(135deg, #e74c3c, #c0392b);
  }
}

/* 状态选项样式 */
.status-option {
  display: flex;
  align-items: center;
  padding: 4px 0;

  .status-dot {
    margin-right: 8px;
  }
}

/* 选中状态 */
:deep(.arco-dropdown-option.selected) {
  background-color: var(--color-primary-light-1);
}

/* 悬停效果 - 类别标签 */
.category-tag {
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  }
}

/* 表格单元格内边距调整 */
.table-page :deep(.arco-table td) {
  padding: 12px 8px;
}

/* 即将到期样式 */
.expiring-soon {
  color: #f53f3f;
  font-weight: 500;
}

.expired {
  color: #86909c;
  text-decoration: line-through;
}
</style>